<template>
  <div class="quotation-form">
    <div class="form-header">
      <h2>创建报价单</h2>
      <div class="actions">
        <el-button @click="saveDraft" :loading="saving">保存草稿</el-button>
        <el-button type="primary" @click="submitQuotation" :loading="submitting">提交报价</el-button>
        <el-button type="success" @click="handleGenerateContract" 
                   :loading="generating">
          {{ quotationForm.status === '已生成合同' ? '重新生成合同' : '生成合同' }}
        </el-button>
      </div>
    </div>

    <el-form :model="quotationForm" :rules="rules" ref="quotationFormRef" label-width="120px">
      <!-- 基本信息 -->
      <el-card class="form-section">
        <template #header>
          <span>报价基本信息</span>
        </template>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="客户代码" prop="customerCode">
              <el-select v-model="quotationForm.customerCode" filterable
                         placeholder="请选择客户代码" @change="handleCustomerChange">
                <el-option v-for="customer in customers" :key="customer.customerCode" 
                          :label="customer.customerCode" :value="customer.customerCode"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户名称" prop="customerName">
              <el-select v-model="quotationForm.customerName" filterable
                         placeholder="请选择客户名称" @change="handleCustomerNameChange">
                <el-option v-for="customer in customers" :key="customer.customerCode" 
                          :label="customer.customerName" :value="customer.customerName"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务员" prop="salesperson">
              <el-select v-model="quotationForm.salesperson" filterable
                         placeholder="请选择业务员">
                <el-option v-for="emp in employees" :key="emp.employeeCode" 
                          :label="emp.employeeName" :value="emp.employeeName"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="合同编号">
              <el-input v-model="quotationForm.contractNo" placeholder="可选"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="订单日期" prop="orderDate">
              <el-date-picker v-model="quotationForm.orderDate" type="date" 
                             value-format="YYYY-MM-DD" placeholder="选择订单日期"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否含税">
              <el-select v-model="quotationForm.isTaxIncluded" placeholder="选择是否含税">
                <el-option label="否" :value="false"/>
                <el-option label="增值税票 13%" :value="true"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="付款方式" prop="paymentMethod">
              <el-select v-model="quotationForm.paymentMethod" filterable allow-create default-first-option
                         placeholder="选择或输入付款方式">
                <el-option label="现金" value="现金"/>
                <el-option label="月结30天" value="月结30天"/>
                <el-option label="月结60天" value="月结60天"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注">
              <el-input v-model="quotationForm.remark" placeholder="备注信息"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 物料信息 -->
      <el-card class="form-section">
        <template #header>
          <div class="card-header">
            <span>物料详情</span>
            <el-button type="primary" size="small" @click="addItem">
            添加物料
          </el-button>
          </div>
        </template>

        <div v-for="(item, index) in quotationForm.items" :key="index" class="item-card">
          <div class="item-header">
            <span class="item-title">物料 {{ index + 1 }}</span>
            <el-button size="small" type="danger" @click="removeItem(index)" plain>
              删除
            </el-button>
          </div>

          <!-- 基本信息区域 -->
          <div class="info-section">
            <h4 class="section-subtitle">基本信息</h4>
            <el-row :gutter="15">
              <el-col :span="8">
                <el-form-item label="产品名称" label-width="80px">
                  <el-input v-model="item.productName" placeholder="请输入产品名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="物料编码" label-width="80px">
                  <el-input v-model="item.materialCode" placeholder="请输入物料编码"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="数量" label-width="80px">
                  <el-input v-model="item.quantity" type="text" class="number-input"
                           @input="value => onQuantityChange(value, item)"
                           @blur="() => formatNumber(item, 'quantity', false)"
                           placeholder="请输入数量"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="6">
                <el-form-item label="层数" label-width="80px">
                  <div v-if="item.layersCustom">
                    <el-input v-model="item.layers" placeholder="请输入层数">
                      <template #append>
                        <el-button @click="item.layersCustom = false; item.layers = ''">返回选择</el-button>
                      </template>
                    </el-input>
                  </div>
                  <el-select v-else v-model="item.layers" placeholder="层数" @change="handleLayersChange(item)">
                    <el-option label="1" value="1"/>
                    <el-option label="2" value="2"/>
                    <el-option label="4" value="4"/>
                    <el-option label="6" value="6"/>
                    <el-option label="无" value="无"/>
                    <el-option label="自定义" value="自定义"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="板厚(mm)" label-width="80px">
                  <div v-if="item.thicknessCustom">
                    <el-input v-model="item.thickness" placeholder="请输入板厚">
                      <template #append>
                        <el-button @click="item.thicknessCustom = false; item.thickness = ''">返回选择</el-button>
                      </template>
                    </el-input>
                  </div>
                  <el-select v-else v-model="item.thickness" placeholder="板厚" @change="handleThicknessChange(item)">
                    <el-option label="0.6" value="0.6"/>
                    <el-option label="0.8" value="0.8"/>
                    <el-option label="1.0" value="1.0"/>
                    <el-option label="1.2" value="1.2"/>
                    <el-option label="1.6" value="1.6"/>
                    <el-option label="2.0" value="2.0"/>
                    <el-option label="2.5" value="2.5"/>
                    <el-option label="3.0" value="3.0"/>
                    <el-option label="无" value="无"/>
                    <el-option label="自定义" value="自定义"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="表面处理" label-width="80px">
                  <div v-if="item.surfaceTreatmentCustom">
                    <el-input v-model="item.surfaceTreatment" placeholder="请输入表面处理">
                      <template #append>
                        <el-button @click="item.surfaceTreatmentCustom = false; item.surfaceTreatment = ''">返回选择</el-button>
                      </template>
                    </el-input>
                  </div>
                  <el-select v-else v-model="item.surfaceTreatment" placeholder="表面处理" @change="handleSurfaceTreatmentChange(item)">
                    <el-option label="有铅喷锡" value="有铅喷锡"/>
                    <el-option label="无铅喷锡" value="无铅喷锡"/>
                    <el-option label="OSP" value="OSP"/>
                    <el-option label="沉金" value="沉金"/>
                    <el-option label="无" value="无"/>
                    <el-option label="自定义" value="自定义"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="阻焊颜色" label-width="80px">
                  <div v-if="item.solderMaskCustom">
                    <el-input v-model="item.solderMask" placeholder="请输入阻焊颜色">
                      <template #append>
                        <el-button @click="item.solderMaskCustom = false; item.solderMask = ''">返回选择</el-button>
                      </template>
                    </el-input>
                  </div>
                  <el-select v-else v-model="item.solderMask" placeholder="阻焊" @change="handleSolderMaskChange(item)">
                    <el-option label="绿油" value="绿油"/>
                    <el-option label="白油" value="白油"/>
                    <el-option label="黑油" value="黑油"/>
                    <el-option label="蓝油" value="蓝油"/>
                    <el-option label="黄油" value="黄油"/>
                    <el-option label="无" value="无"/>
                    <el-option label="自定义" value="自定义"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="6">
                <el-form-item label="字符颜色" label-width="80px">
                  <div v-if="item.characterCustom">
                    <el-input v-model="item.character" placeholder="请输入字符颜色">
                      <template #append>
                        <el-button @click="item.characterCustom = false; item.character = ''">返回选择</el-button>
                      </template>
                    </el-input>
                  </div>
                  <el-select v-else v-model="item.character" placeholder="字符" @change="handleCharacterChange(item)">
                    <el-option label="白字" value="白字"/>
                    <el-option label="黑字" value="黑字"/>
                    <el-option label="无" value="无"/>
                    <el-option label="自定义" value="自定义"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="板材" label-width="80px">
                  <el-input v-model="item.boardMaterial" placeholder="如 FR-4"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="交货尺寸" label-width="80px">
                  <el-input v-model="item.deliverySize" placeholder="如 100x100"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="拼版" label-width="80px">
                  <el-input v-model="item.panelization" placeholder="如 1x1" @input="() => calculateAmount(item)"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="6">
                <el-form-item label="内铜厚度" label-width="80px">
                  <div v-if="item.innerCopperCustom">
                    <el-input v-model="item.innerCopper" placeholder="请输入内铜厚度">
                      <template #append>
                        <el-button @click="item.innerCopperCustom = false; item.innerCopper = ''">返回选择</el-button>
                      </template>
                    </el-input>
                  </div>
                  <el-select v-else v-model="item.innerCopper" placeholder="内铜" @change="handleInnerCopperChange(item)">
                    <el-option label="0.5oz" value="0.5oz"/>
                    <el-option label="1oz" value="1oz"/>
                    <el-option label="无" value="无"/>
                    <el-option label="自定义" value="自定义"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="外铜厚度" label-width="80px">
                  <div v-if="item.outerCopperCustom">
                    <el-input v-model="item.outerCopper" placeholder="请输入外铜厚度">
                      <template #append>
                        <el-button @click="item.outerCopperCustom = false; item.outerCopper = ''">返回选择</el-button>
                      </template>
                    </el-input>
                  </div>
                  <el-select v-else v-model="item.outerCopper" placeholder="外铜" @change="handleOuterCopperChange(item)">
                    <el-option label="0.5oz" value="0.5oz"/>
                    <el-option label="1oz" value="1oz"/>
                    <el-option label="1.5oz" value="1.5oz"/>
                    <el-option label="2oz" value="2oz"/>
                    <el-option label="无" value="无"/>
                    <el-option label="自定义" value="自定义"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="过孔工艺" label-width="80px">
                  <div v-if="item.viaProcessCustom">
                    <el-input v-model="item.viaProcess" placeholder="请输入过孔工艺">
                      <template #append>
                        <el-button @click="item.viaProcessCustom = false; item.viaProcess = ''">返回选择</el-button>
                      </template>
                    </el-input>
                  </div>
                  <el-select v-else v-model="item.viaProcess" placeholder="过孔工艺" @change="handleViaProcessChange(item)">
                    <el-option label="过孔盖油" value="过孔盖油"/>
                    <el-option label="过孔塞油" value="过孔塞油"/>
                    <el-option label="过孔开窗" value="过孔开窗"/>
                    <el-option label="树脂塞油" value="树脂塞油"/>
                    <el-option label="无" value="无"/>
                    <el-option label="自定义" value="自定义"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="测试方式" label-width="80px">
                  <div v-if="item.testingCustom">
                    <el-input v-model="item.testing" placeholder="请输入测试方式">
                      <template #append>
                        <el-button @click="item.testingCustom = false; item.testing = ''">返回选择</el-button>
                      </template>
                    </el-input>
                  </div>
                  <el-select v-else v-model="item.testing" placeholder="测试" @change="handleTestingChange(item)">
                    <el-option label="飞针测试" value="飞针测试"/>
                    <el-option label="测试架" value="测试架"/>
                    <el-option label="无" value="无"/>
                    <el-option label="自定义" value="自定义"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="8">
                <el-form-item label="单价" label-width="80px">
                  <el-input v-model="item.unitPrice" type="text" class="number-input"
                           @input="value => onUnitPriceChange(value, item)"
                           @blur="() => formatUnitPrice(item)"
                           placeholder="单价 (无为自动计算)"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合计金额" label-width="80px">
                  <el-input v-model="item.totalAmount" type="text" class="number-input"
                           @input="value => onItemAmountChange(value, item)"
                           @blur="() => formatItemAmount(item)"
                           placeholder="请输入合计金额"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="出货日期" label-width="80px">
                  <el-date-picker v-model="item.deliveryDate" type="date"
                                 value-format="YYYY-MM-DD" placeholder="出货日期"/>
                </el-form-item>
              </el-col>
            </el-row>
            
            <!-- 费用明细区域 -->
            <div class="fee-section">
<!--              <h5 class="fee-subtitle">费用明细</h5>-->
              <el-row :gutter="15">
                <el-col :span="6">
                  <el-form-item label="样板费" label-width="80px">
                    <el-input v-model="item.sampleFee" type="text" class="number-input"
                             @input="value => onFeeFieldChange(value, item, 'sampleFee')"
                             @blur="() => formatFeeField(item, 'sampleFee')"
                             placeholder="样板费"/>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="工程费" label-width="80px">
                    <el-input v-model="item.engineeringFee" type="text" class="number-input"
                             @input="value => onFeeFieldChange(value, item, 'engineeringFee')"
                             @blur="() => formatFeeField(item, 'engineeringFee')"
                             placeholder="工程费"/>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="加急费" label-width="80px">
                    <el-input v-model="item.urgentFee" type="text" class="number-input"
                             @input="value => onFeeFieldChange(value, item, 'urgentFee')"
                             @blur="() => formatFeeField(item, 'urgentFee')"
                             placeholder="加急费"/>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="阻抗费" label-width="80px">
                    <el-input v-model="item.impedanceFee" type="text" class="number-input"
                             @input="value => onFeeFieldChange(value, item, 'impedanceFee')"
                             @blur="() => formatFeeField(item, 'impedanceFee')"
                             placeholder="阻抗费"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="15">
                <el-col :span="6">
                  <el-form-item label="测试架费" label-width="80px">
                    <el-input v-model="item.testingFee" type="text" class="number-input"
                             @input="value => onFeeFieldChange(value, item, 'testingFee')"
                             @blur="() => formatFeeField(item, 'testingFee')"
                             placeholder="测试架费"/>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="运费" label-width="80px">
                    <el-input v-model="item.shippingFee" type="text" class="number-input"
                             @input="value => onFeeFieldChange(value, item, 'shippingFee')"
                             @blur="() => formatFeeField(item, 'shippingFee')"
                             placeholder="运费"/>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="税金" label-width="80px">
                    <el-input v-model="item.taxAmount" type="text" class="number-input"
                             @input="value => onFeeFieldChange(value, item, 'taxAmount')"
                             @blur="() => formatFeeField(item, 'taxAmount')"
                             placeholder="税金"/>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="其他费用" label-width="80px">
                    <el-input v-model="item.otherFee" type="text" class="number-input"
                             @input="value => onFeeFieldChange(value, item, 'otherFee')"
                             @blur="() => formatFeeField(item, 'otherFee')"
                             placeholder="其他费用"/>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            
            <!-- 自定义字段区域 -->
            <div v-if="item.customFields && item.customFields.length > 0" class="custom-fields-section">
              <h5 class="fee-subtitle">自定义字段</h5>
              <el-row v-for="(customField, fieldIndex) in item.customFields" :key="fieldIndex" :gutter="15" class="custom-field-row">
                <el-col :span="8">
                  <el-form-item label="字段名" label-width="80px">
                    <el-input v-model="customField.name" placeholder="请输入字段名"/>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="字段值" label-width="80px">
                    <el-input v-model="customField.value" type="text" class="number-input"
                             @input="value => onCustomFieldChange(value, customField)"
                             @blur="() => formatCustomField(customField)"
                             placeholder="请输入金额"/>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="" label-width="80px">
                    <el-button type="danger" size="small" @click="removeCustomField(item, fieldIndex)" plain>
                      删除
                    </el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>

          <!-- 价格计算区域 -->
          <div class="info-section">
            <h4 class="section-subtitle">价格计算</h4>
            <el-row :gutter="15">
              <el-col :span="6">
                <el-form-item label="宽度(mm)" label-width="80px">
                  <el-input v-model="item.calculation.widthMm" type="text" class="number-input"
                           @input="value => onCalculationFieldChange(value, item, 'widthMm')"
                           @blur="() => formatNumber(item.calculation, 'widthMm', true)"
                           placeholder="宽度"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="长度(mm)" label-width="80px">
                  <el-input v-model="item.calculation.lengthMm" type="text" class="number-input"
                           @input="value => onCalculationFieldChange(value, item, 'lengthMm')"
                           @blur="() => formatNumber(item.calculation, 'lengthMm', true)"
                           placeholder="长度"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="订单面积" label-width="80px">
                  <el-input :value="formatDisplayNumber(item.calculation.orderAreaMm, 4) + ' mm²'" readonly disabled class="readonly-field"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="平米价(元)" label-width="80px">
                  <el-input v-model="item.calculation.pricePerSqm" type="text" class="number-input"
                           @input="value => onCalculationFieldChange(value, item, 'pricePerSqm')"
                           @blur="() => formatNumber(item.calculation, 'pricePerSqm', true)"
                           placeholder="平米价"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="6">
                <el-form-item label="未税单价" label-width="80px">
                  <el-input :value="formatDisplayNumber(item.calculation.untaxUnitPrice, 4) + ' 元'" readonly disabled class="readonly-field"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="未税金额" label-width="80px">
                  <el-input :value="formatDisplayNumber(item.calculation.untaxAmount, 2) + ' 元'" readonly disabled class="readonly-field"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="测试架费用" label-width="80px">
                  <el-input v-model="item.calculation.testingFee" type="text" class="number-input"
                           @input="value => onCalculationFieldChange(value, item, 'testingFee')"
                           @blur="() => formatNumber(item.calculation, 'testingFee', true)"
                           placeholder="测试架费用"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="未税总金额" label-width="80px">
                  <el-input :value="formatDisplayNumber(item.calculation.untaxTotalAmount, 2) + ' 元'" readonly disabled class="readonly-field"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item label="含税单价" label-width="80px">
                  <el-input :value="formatDisplayNumber(item.calculation.taxUnitPrice, 4) + ' 元'" readonly disabled class="readonly-field"/>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 成本明细区域 -->
          <div class="info-section">
            <h4 class="section-subtitle">成本明细</h4>
            <el-row :gutter="15">
              <el-col :span="6">
                <el-form-item label="起步价" label-width="80px">
                  <el-input v-model="item.costs.basePrice" type="text" class="number-input"
                           @input="value => onCostFieldChange(value, item, 'basePrice')"
                           @blur="() => formatNumber(item.costs, 'basePrice', true)"
                           placeholder="起步价"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="阻燃费" label-width="80px">
                  <el-input v-model="item.costs.flameRetardantFee" type="text" class="number-input"
                           @input="value => onCostFieldChange(value, item, 'flameRetardantFee')"
                           @blur="() => formatNumber(item.costs, 'flameRetardantFee', true)"
                           placeholder="阻燃费"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="沉铜费" label-width="80px">
                  <el-input v-model="item.costs.copperPlatingFee" type="text" class="number-input"
                           @input="value => onCostFieldChange(value, item, 'copperPlatingFee')"
                           @blur="() => formatNumber(item.costs, 'copperPlatingFee', true)"
                           placeholder="沉铜费"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="表面处理费" label-width="80px">
                  <el-input v-model="item.costs.surfaceTreatmentFee" type="text" class="number-input"
                           @input="value => onCostFieldChange(value, item, 'surfaceTreatmentFee')"
                           @blur="() => formatNumber(item.costs, 'surfaceTreatmentFee', true)"
                           placeholder="表面处理费"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="6">
                <el-form-item label="工程费" label-width="80px">
                  <el-input v-model="item.costs.engineeringFee" type="text" class="number-input"
                           @input="value => onCostFieldChange(value, item, 'engineeringFee')"
                           @blur="() => formatNumber(item.costs, 'engineeringFee', true)"
                           placeholder="工程费"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="运费" label-width="80px">
                  <el-input v-model="item.costs.shippingFee" type="text" class="number-input"
                           @input="value => onCostFieldChange(value, item, 'shippingFee')"
                           @blur="() => formatNumber(item.costs, 'shippingFee', true)"
                           placeholder="运费"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="铜厚费" label-width="80px">
                  <el-input v-model="item.costs.copperThicknessFee" type="text" class="number-input"
                           @input="value => onCostFieldChange(value, item, 'copperThicknessFee')"
                           @blur="() => formatNumber(item.costs, 'copperThicknessFee', true)"
                           placeholder="铜厚费"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="成本合计" label-width="80px">
                  <el-input :value="formatDisplayNumber(getCostTotal(item.costs), 2) + ' 元'" readonly disabled class="readonly-field"/>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 备注区域 -->
          <div class="info-section">
            <h4 class="section-subtitle">备注信息</h4>
            <el-row :gutter="15">
              <el-col :span="24">
                <el-form-item label="备注" label-width="80px">
                  <el-input v-model="item.itemRemark" type="textarea" :rows="3" 
                           placeholder="请输入物料备注信息"/>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-card>
      
      <!-- 汇总信息 -->
      <el-card class="form-section">
        <template #header>
          <span>汇总信息</span>
        </template>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="总金额">
              <el-input :value="formatDisplayNumber(computedTotalAmount, 2) + ' 元'" readonly disabled class="readonly-field"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态">
              <el-tag :type="getStatusTagType(quotationForm.status)" size="large">
                {{ quotationForm.status || '草稿' }}
              </el-tag>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { quotationAPI, customerAPI, employeeAPI } from '../utils/api'

export default {
  name: 'QuotationForm',
  setup() {
    const router = useRouter()
    const quotationFormRef = ref(null)
    
    // 加载状态
    const saving = ref(false)
    const submitting = ref(false)
    const generating = ref(false)
    
    // 表单数据
    const quotationForm = reactive({
      customerCode: '',
      customerName: '',
      salesperson: '',
      contractNo: '',
      orderDate: '',
      isTaxIncluded: false,
      paymentMethod: '',
      totalAmount: 0,
      status: '草稿',
      remark: '',
      items: []
    })
    
    // 选项数据
    const customers = ref([])
    const employees = ref([])
    
    // 表单验证规则
    const rules = {
      customerCode: [{ required: true, message: '请选择客户代码', trigger: 'change' }],
      customerName: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
      salesperson: [{ required: true, message: '请选择业务员', trigger: 'change' }],
      orderDate: [{ required: true, message: '请选择订单日期', trigger: 'change' }],
      paymentMethod: [{ required: true, message: '请选择付款方式', trigger: 'change' }]
    }
    
    // 添加物料
    const addItem = () => {
      const itemNo = quotationForm.items.length + 1
      quotationForm.items.push({
        itemNo,
        productName: '',
        materialCode: '',
        layers: '4',
        thickness: '1.6',
        surfaceTreatment: '无铅喷锡',
        solderMask: '绿油',
        character: '白字',
        boardMaterial: 'FR-4',
        deliverySize: '',
        panelization: '',
        innerCopper: '1oz',
        outerCopper: '1oz',
        viaProcess: '',
        testing: '',
        testingFee: 0,
        isUrgent: false,
        quantity: 100,
        unitPrice: '无',
        sampleFee: 0,
        engineeringFee: 0,
        urgentFee: 0,
        impedanceFee: 0,
        testingFee: 0,
        shippingFee: 0,
        taxAmount: 0,
        otherFee: 0,
        totalAmount: 0,
        deliveryDate: '',
        itemRemark: '',
        isTaxIncluded: false,
        paymentMethod: '',
        customFields: [],
        // 自定义输入控制标志
        layersCustom: false,
        thicknessCustom: false,
        surfaceTreatmentCustom: false,
        solderMaskCustom: false,
        characterCustom: false,
        innerCopperCustom: false,
        outerCopperCustom: false,
        viaProcessCustom: false,
        testingCustom: false,
        calculation: {
          widthMm: 0,
          lengthMm: 0,
          orderAreaMm: 0,
          pricePerSqm: 0,
          untaxUnitPrice: 0,
          untaxAmount: 0,
          testingFee: 0,
          untaxTotalAmount: 0,
          taxTotalAmount: 0,
          taxUnitPrice: 0
        },
        costs: {
          basePrice: 0,
          flameRetardantFee: 0,
          copperPlatingFee: 0,
          surfaceTreatmentFee: 0,
          engineeringFee: 0,
          shippingFee: 0,
          copperThicknessFee: 0,
          oversizeHoleFee: 0,
          impedanceFee: 0,
          halfHoleFee: 0,
          mergePanelFee: 0,
          resinPlugHoleFee: 0,
          goldFingerFee: 0,
          totalCost: 0
        }
      })
    }
    
    // 删除物料
    const removeItem = (index) => {
      quotationForm.items.splice(index, 1)
      // 重新编号
      quotationForm.items.forEach((item, idx) => {
        item.itemNo = idx + 1
      })
      calculateTotalAmount()
    }

    // 处理层数选择变化
    const handleLayersChange = (item) => {
      if (item.layers === '自定义') {
        item.layersCustom = true
        item.layers = ''
      }
    }

    // 处理板厚选择变化
    const handleThicknessChange = (item) => {
      if (item.thickness === '自定义') {
        item.thicknessCustom = true
        item.thickness = ''
      }
    }

    // 处理表面处理选择变化
    const handleSurfaceTreatmentChange = (item) => {
      if (item.surfaceTreatment === '自定义') {
        item.surfaceTreatmentCustom = true
        item.surfaceTreatment = ''
      }
    }

    // 处理阻焊颜色选择变化
    const handleSolderMaskChange = (item) => {
      if (item.solderMask === '自定义') {
        item.solderMaskCustom = true
        item.solderMask = ''
      }
    }

    // 处理字符颜色选择变化
    const handleCharacterChange = (item) => {
      if (item.character === '自定义') {
        item.characterCustom = true
        item.character = ''
      }
    }

    // 处理内铜厚度选择变化
    const handleInnerCopperChange = (item) => {
      if (item.innerCopper === '自定义') {
        item.innerCopperCustom = true
        item.innerCopper = ''
      }
    }

    // 处理外铜厚度选择变化
    const handleOuterCopperChange = (item) => {
      if (item.outerCopper === '自定义') {
        item.outerCopperCustom = true
        item.outerCopper = ''
      }
    }

    // 处理过孔工艺选择变化
    const handleViaProcessChange = (item) => {
      if (item.viaProcess === '自定义') {
        item.viaProcessCustom = true
        item.viaProcess = ''
      }
    }

    // 处理测试方式选择变化
    const handleTestingChange = (item) => {
      if (item.testing === '自定义') {
        item.testingCustom = true
        item.testing = ''
      }
    }
    
    // 解析拼版数量的辅助函数
    const parsePanelization = (panelizationStr) => {
      if (!panelizationStr || panelizationStr.trim() === '') {
        return 1; // 默认为1，避免除零错误
      }
      
      // 处理类似 "2x2", "1x3", "4x1" 等格式
      const match = panelizationStr.toString().match(/(\d+)[\s]*[x×*][\s]*(\d+)/i);
      if (match) {
        const width = parseInt(match[1]);
        const height = parseInt(match[2]);
        return width * height;
      }
      
      // 如果只是一个数字，直接返回
      const num = parseInt(panelizationStr);
      if (!isNaN(num) && num > 0) {
        return num;
      }
      
      // 默认返回1
      return 1;
    }
    
    // 新的计算逻辑 - 根据用户要求重新实现
    const calculateAmount = (row) => {
      if (!row.calculation) return
      
      const calc = row.calculation
      
      // 确保所有输入值都转换为数字类型
      const quantity = Number(row.quantity) || 0
      const width = Number(calc.widthMm) || 0
      const length = Number(calc.lengthMm) || 0
      const pricePerSqm = Number(calc.pricePerSqm) || 0
      const testingFee = Number(calc.testingFee) || 0
      const panelCount = parsePanelization(row.panelization)
      
      // 订单面积mm 公式=长*宽/1000000/拼版*数量
      if (width && length && quantity && panelCount > 0) {
        calc.orderAreaMm = Number(((length * width / 1000000 / panelCount) * quantity).toFixed(4))
      } else {
        calc.orderAreaMm = 0
      }
      
      // 未税金额 公式=订单面积*平米价
      calc.untaxAmount = Number((calc.orderAreaMm * pricePerSqm).toFixed(2))
      
      // 未税总金额 公式=未税金额+测试架费用 - 确保数值相加
      calc.untaxTotalAmount = Number((calc.untaxAmount + testingFee).toFixed(2))
      
      // 含税总金额 公式=未税总金额*110%
      calc.taxTotalAmount = Number((calc.untaxTotalAmount * 1.1).toFixed(2))
      
      // 未税单价（元）公式=未税金额/数量
      if (quantity > 0) {
        calc.untaxUnitPrice = Number((calc.untaxAmount / quantity).toFixed(4))
      } else {
        calc.untaxUnitPrice = 0
      }
      
      // 含税单价 公式=未税单价*110%
      calc.taxUnitPrice = Number((calc.untaxUnitPrice * 1.1).toFixed(4))
      
      // 更新物料项的总金额 - 使用含税总金额
      row.totalAmount = calc.taxTotalAmount
      
      // 如果用户没有手动输入单价，则使用计算出的含税单价
      if (row.unitPrice === '无' || row.unitPrice === 0 || row.unitPrice === '') {
        row.unitPrice = calc.taxUnitPrice.toFixed(2)
      }
      
      calculateTotalAmount()
    }
    
    // 计算成本合计 - 只计算界面上显示的7个字段
    const calculateTotalCost = (costs) => {
      if (!costs) return 0
      return (costs.basePrice || 0) + 
             (costs.flameRetardantFee || 0) + 
             (costs.copperPlatingFee || 0) + 
             (costs.surfaceTreatmentFee || 0) + 
             (costs.engineeringFee || 0) + 
             (costs.shippingFee || 0) + 
             (costs.copperThicknessFee || 0)
    }

    // 获取成本合计 - 实时计算界面显示的7个费用字段之和
    const getCostTotal = (costs) => {
      if (!costs) return 0
      
      // 确保所有字段都是数字类型
      const basePrice = Number(costs.basePrice) || 0
      const flameRetardantFee = Number(costs.flameRetardantFee) || 0
      const copperPlatingFee = Number(costs.copperPlatingFee) || 0
      const surfaceTreatmentFee = Number(costs.surfaceTreatmentFee) || 0
      const engineeringFee = Number(costs.engineeringFee) || 0
      const shippingFee = Number(costs.shippingFee) || 0
      const copperThicknessFee = Number(costs.copperThicknessFee) || 0
      
      return basePrice + flameRetardantFee + copperPlatingFee + 
             surfaceTreatmentFee + engineeringFee + shippingFee + 
             copperThicknessFee
    }
    
    // 计算总金额 - 注释掉自动计算，改为手动输入
    const calculateTotalAmount = () => {
      // 用户要求总金额手动输入，不进行自动计算
      // const total = quotationForm.items.reduce((sum, item) => {
      //   return sum + (item.totalAmount || 0)
      // }, 0)
      // quotationForm.totalAmount = total
    }
    
    // 处理客户代码选择变化
    const handleCustomerChange = (customerCode) => {
      const selectedCustomer = customers.value.find(c => c.customerCode === customerCode)
      if (selectedCustomer) {
        quotationForm.customerName = selectedCustomer.customerName
      }
    }

    // 处理客户名称选择变化
    const handleCustomerNameChange = (customerName) => {
      const selectedCustomer = customers.value.find(c => c.customerName === customerName)
      if (selectedCustomer) {
        quotationForm.customerCode = selectedCustomer.customerCode
      }
    }
    
    // 获取状态标签类型
    const getStatusTagType = (status) => {
      switch (status) {
        case '草稿': return 'info'
        case '已提交': return 'primary'
        case '已生成合同': return 'success'
        case '已审核': return 'success'
        case '已拒绝': return 'danger'
        default: return 'info'
      }
    }
    
    // 数据预处理：将customFields数组转换为JSON字符串，并确保数值字段为数字类型
    const preprocessQuotationData = (data) => {
      const processedData = { ...data }
      
      if (processedData.items && Array.isArray(processedData.items)) {
        processedData.items = processedData.items.map(item => {
          const processedItem = { ...item }
          
          // 将customFields数组转换为JSON字符串
          if (processedItem.customFields && Array.isArray(processedItem.customFields)) {
            processedItem.customFields = JSON.stringify(processedItem.customFields)
          }
          
          // 确保所有数值字段都是数字类型
          const numberFields = ['quantity', 'unitPrice', 'sampleFee', 'engineeringFee', 'urgentFee', 
                               'impedanceFee', 'testingFee', 'shippingFee', 'taxAmount', 'otherFee', 'totalAmount']
          
          numberFields.forEach(field => {
            if (processedItem[field] !== null && processedItem[field] !== undefined && processedItem[field] !== '') {
              const value = processedItem[field]
              if (field === 'unitPrice' && (value === '无' || value === 'N/A')) {
                // 保持"无"这样的特殊值
                processedItem[field] = value
              } else {
                processedItem[field] = Number(value) || 0
              }
            }
          })
          
          // 处理calculation对象
          if (processedItem.calculation) {
            const calcFields = ['widthMm', 'lengthMm', 'orderAreaMm', 'pricePerSqm', 'untaxUnitPrice', 
                               'untaxAmount', 'testingFee', 'untaxTotalAmount', 'taxTotalAmount', 'taxUnitPrice']
            
            calcFields.forEach(field => {
              if (processedItem.calculation[field] !== null && processedItem.calculation[field] !== undefined) {
                processedItem.calculation[field] = Number(processedItem.calculation[field]) || 0
              }
            })
          }
          
          // 处理costs对象
          if (processedItem.costs) {
            const costFields = ['basePrice', 'flameRetardantFee', 'copperPlatingFee', 'surfaceTreatmentFee',
                               'engineeringFee', 'shippingFee', 'copperThicknessFee', 'oversizeHoleFee',
                               'impedanceFee', 'halfHoleFee', 'mergePanelFee', 'resinPlugHoleFee',
                               'goldFingerFee', 'totalCost']
            
            costFields.forEach(field => {
              if (processedItem.costs[field] !== null && processedItem.costs[field] !== undefined) {
                processedItem.costs[field] = Number(processedItem.costs[field]) || 0
              }
            })
          }
          
          return processedItem
        })
      }
      
      // 确保顶级数值字段也是数字类型
      if (processedData.totalAmount !== null && processedData.totalAmount !== undefined) {
        processedData.totalAmount = Number(processedData.totalAmount) || 0
      }
      
      return processedData
    }

    // 数据后处理：将customFields JSON字符串转换为数组
    const postprocessQuotationData = (data) => {
      if (data && data.items && Array.isArray(data.items)) {
        data.items = data.items.map(item => {
          const processedItem = { ...item }
          
          // 将customFields JSON字符串转换为数组
          if (processedItem.customFields && typeof processedItem.customFields === 'string') {
            try {
              processedItem.customFields = JSON.parse(processedItem.customFields)
            } catch (e) {
              // 如果解析失败，设置为空数组
              processedItem.customFields = []
            }
          } else if (!processedItem.customFields) {
            // 如果没有customFields，设置为空数组
            processedItem.customFields = []
          }
          
          return processedItem
        })
      }
      
      return data
    }

    // 保存草稿
    const saveDraft = async () => {
      try {
        saving.value = true
        
        // 获取当前登录用户信息
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        
        // 设置创建人和状态
        const quotationData = preprocessQuotationData({
          ...quotationForm,
          createdBy: userInfo.username || userInfo.employeeName || '系统用户',
          status: '草稿'
        })
        
        let response
        if (quotationForm.id) {
          // 更新现有草稿
          response = await quotationAPI.updateQuotation(quotationForm.id, quotationData)
        } else {
          // 创建新草稿
          response = await quotationAPI.createQuotation(quotationData)
        }
        
        if (response.code === 200) {
          // 对返回的数据进行后处理
          const processedData = postprocessQuotationData(response.data)
          Object.assign(quotationForm, processedData)
          ElMessage.success('草稿保存成功')
        } else {
          ElMessage.error(response.message || '草稿保存失败')
        }
      } catch (error) {
        console.error('保存草稿失败:', error)
        ElMessage.error(error.message || '保存草稿失败')
      } finally {
        saving.value = false
      }
    }
    
    // 提交报价单
    const submitQuotation = async () => {
      if (!quotationFormRef.value) return
      
      try {
        const valid = await quotationFormRef.value.validate()
        if (valid) {
          submitting.value = true
          
          // 获取当前登录用户信息
          const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
          
          // 设置创建人和状态
          const quotationData = preprocessQuotationData({
            ...quotationForm,
            createdBy: userInfo.username || userInfo.employeeName || '系统用户',
            status: '已提交'
          })
          
          let response
          if (quotationForm.id) {
            // 如果是已有报价单，调用提交接口
            response = await quotationAPI.submitQuotation(quotationForm.id)
          } else {
            // 创建新报价单并直接设置为已提交状态
            response = await quotationAPI.createQuotation(quotationData)
          }
          
          if (response.code === 200) {
            // 对返回的数据进行后处理
            const processedData = postprocessQuotationData(response.data)
            Object.assign(quotationForm, processedData)
            ElMessage.success('报价单提交成功')
          } else {
            ElMessage.error(response.message || '报价单提交失败')
          }
        }
      } catch (error) {
        console.error('提交报价单失败:', error)
        ElMessage.error(error.message || '提交报价单失败')
      } finally {
        submitting.value = false
      }
    }
    
    // 生成合同
    const generateContract = async () => {
      try {
        const message = quotationForm.status === '已生成合同' 
          ? '确认重新生成合同吗？这将覆盖原有的合同内容。'
          : '确认生成合同吗？生成后将无法修改报价单内容。'
        
        const confirmed = await ElMessageBox.confirm(
          message, 
          '生成合同确认', 
          {
            type: 'warning',
            confirmButtonText: '确认生成',
            cancelButtonText: '取消'
          }
        )
        
        if (confirmed) {
          generating.value = true
          const response = await quotationAPI.generateContract(quotationForm.id)
          
          if (response.code === 200) {
            quotationForm.status = '已生成合同'
            ElMessage.success('合同生成成功！您可以前往合同审核页面查看和下载合同。')
            
            // 询问是否跳转到合同审核页面
            setTimeout(async () => {
              try {
                await ElMessageBox.confirm('是否立即跳转到合同审核页面查看合同？', '提示', {
                  type: 'info',
                  confirmButtonText: '立即查看',
                  cancelButtonText: '稍后查看'
                })
                // 这里可以添加路由跳转逻辑
                router.push('/contract-audit')
              } catch (e) {
                // 用户选择稍后查看，不做处理
              }
            }, 1000)
          } else {
            ElMessage.error(response.message || '合同生成失败')
          }
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('生成合同失败:', error)
          ElMessage.error('生成合同失败，请稍后重试')
        }
      } finally {
        generating.value = false
      }
    }
    
    // 处理生成合同（智能提交+生成）
    const handleGenerateContract = async () => {
      try {
        // 如果报价单还没有ID（未保存），先验证并保存
        if (!quotationForm.id) {
          if (!quotationFormRef.value) {
            ElMessage.error('表单引用不可用，请刷新页面后重试')
            return
          }
          
          const valid = await quotationFormRef.value.validate()
          if (!valid) {
            ElMessage.warning('请完善必填信息后再生成合同')
            return
          }
          
          // 先保存报价单
          ElMessage.info('正在保存报价单...')
          submitting.value = true
          
          try {
            // 获取当前登录用户信息
            const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
            
            const quotationData = preprocessQuotationData({
              ...quotationForm,
              createdBy: userInfo.username || userInfo.employeeName || '系统用户',
              status: '草稿'
            })
            
            const response = await quotationAPI.createQuotation(quotationData)
            if (response.code === 200) {
              // 对返回的数据进行后处理
              const processedData = postprocessQuotationData(response.data)
              Object.assign(quotationForm, processedData)
              ElMessage.success('报价单保存成功')
            } else {
              ElMessage.error(response.message || '报价单保存失败')
              return
            }
          } catch (error) {
            console.error('保存报价单失败:', error)
            ElMessage.error('保存报价单失败，请稍后重试')
            return
          } finally {
            submitting.value = false
          }
        }
        
        // 如果状态不是"已提交"，先提交报价单
        if (quotationForm.status === '草稿') {
          ElMessage.info('正在提交报价单...')
          
          try {
            // 调用提交接口
            const submitResponse = await quotationAPI.submitQuotation(quotationForm.id)
            if (submitResponse.code === 200) {
              quotationForm.status = '已提交'
              ElMessage.success('报价单提交成功')
            } else {
              ElMessage.error(submitResponse.message || '报价单提交失败')
              return
            }
          } catch (error) {
            console.error('提交报价单失败:', error)
            ElMessage.error('提交报价单失败，请稍后重试')
            return
          }
        }
        
        // 现在生成合同
        await generateContract()
        
      } catch (error) {
        console.error('生成合同过程出错:', error)
        ElMessage.error('生成合同失败，请稍后重试')
      }
    }
    
    // 获取客户选项
    const fetchCustomers = async () => {
      try {
        const response = await customerAPI.getAllCustomers()
        if (response.code === 200) {
          customers.value = response.data
        }
      } catch (error) {
        console.error('获取客户列表失败:', error)
      }
    }
    
    // 获取业务员选项
    const fetchEmployees = async () => {
      try {
        const response = await employeeAPI.getAllEmployees()
        if (response.code === 200) {
          employees.value = response.data
        }
      } catch (error) {
        console.error('获取业务员列表失败:', error)
      }
    }
    
    // 监听含税状态变化
    watch(() => quotationForm.isTaxIncluded, () => {
      quotationForm.items.forEach(item => {
        calculateAmount(item)
      })
    })
    
    // 数字格式化函数
    const formatDisplayNumber = (value, decimals = 2) => {
      if (value === null || value === undefined || value === '') {
        return decimals === 0 ? '0' : '0.' + '0'.repeat(decimals)
      }
      const num = typeof value === 'string' ? parseFloat(value) : value
      return isNaN(num) ? (decimals === 0 ? '0' : '0.' + '0'.repeat(decimals)) : num.toFixed(decimals)
    }

    // 格式化输入框数值 - 确保金额字段保留两位小数
    const formatNumber = (obj, prop, allowDecimal = true) => {
      const value = obj[prop]
      if (value === null || value === undefined || value === '') {
        obj[prop] = allowDecimal ? '0.00' : '0'
        return
      }
      
      const num = typeof value === 'string' ? parseFloat(value) : value
      if (!isNaN(num)) {
        // 对金额相关字段强制保留两位小数
        const isMoneyField = ['basePrice', 'flameRetardantFee', 'copperPlatingFee', 'surfaceTreatmentFee', 
                              'engineeringFee', 'shippingFee', 'copperThicknessFee', 'testingFee',
                              'pricePerSqm', 'totalAmount'].includes(prop)
        obj[prop] = isMoneyField ? num.toFixed(2) : (allowDecimal ? num.toFixed(2) : num.toString())
      } else {
        obj[prop] = allowDecimal ? '0.00' : '0'
      }
    }

    // 格式化单价字段（特殊处理"无"的情况）
    const formatUnitPrice = (row) => {
      const value = row.unitPrice
      if (value === '无' || value === '') {
        row.unitPrice = '无'
        return
      }
      
      const num = typeof value === 'string' ? parseFloat(value) : value
      if (!isNaN(num)) {
        row.unitPrice = num.toFixed(2)
      } else {
        row.unitPrice = '无'
      }
    }

    // 处理数量变化
    const onQuantityChange = (value, row) => {
      // 只允许整数
      const filteredValue = value.replace(/\D/g, '')
      row.quantity = filteredValue === '' ? 0 : parseInt(filteredValue)
      
      // 重新计算
      calculateAmount(row)
    }

    // 处理单价变化
    const onUnitPriceChange = (value, row) => {
      // 如果是"无"，保持不变
      if (value === '无') {
        row.unitPrice = '无'
        return
      }
      
      // 允许数字和小数点
      let filteredValue = value.replace(/[^\d.]/g, '')
      
      // 确保只有一个小数点
      const parts = filteredValue.split('.')
      if (parts.length > 2) {
        filteredValue = parts[0] + '.' + parts.slice(1).join('')
      }
      
      row.unitPrice = filteredValue
    }

    // 处理价格计算字段变化 - 修正小数点支持
    const onCalculationFieldChange = (value, row, field) => {
      // 允许数字、小数点和负号
      let filteredValue = value.replace(/[^\d.-]/g, '')
      
      // 确保只有一个小数点
      const parts = filteredValue.split('.')
      if (parts.length > 2) {
        filteredValue = parts[0] + '.' + parts.slice(1).join('')
      }
      
      // 保存原始字符串值，允许输入过程中的中间状态
      row.calculation[field] = filteredValue
      
      // 只有当值是有效数字时才重新计算
      const numValue = parseFloat(filteredValue)
      if (!isNaN(numValue) || filteredValue === '' || filteredValue === '.') {
        calculateAmount(row)
      }
    }

    // 处理成本字段变化 - 修正小数点支持
    const onCostFieldChange = (value, row, field) => {
      // 允许数字、小数点和负号
      let filteredValue = value.replace(/[^\d.-]/g, '')
      
      // 确保只有一个小数点
      const parts = filteredValue.split('.')
      if (parts.length > 2) {
        filteredValue = parts[0] + '.' + parts.slice(1).join('')
      }
      
      // 保存原始字符串值，允许输入过程中的中间状态
      row.costs[field] = filteredValue
      
      // 成本合计会通过 getCostTotal(item.costs) 自动计算
      // Vue的响应式系统会自动检测到costs对象的变化并更新界面
    }

    // 处理物料合计金额变化
    const onItemAmountChange = (value, item) => {
      // 允许数字、小数点和负号
      let filteredValue = value.replace(/[^\d.-]/g, '')
      
      // 确保只有一个小数点
      const parts = filteredValue.split('.')
      if (parts.length > 2) {
        filteredValue = parts[0] + '.' + parts.slice(1).join('')
      }
      
      item.totalAmount = filteredValue
    }

    // 格式化物料合计金额
    const formatItemAmount = (item) => {
      const value = item.totalAmount
      if (value === null || value === undefined || value === '') {
        item.totalAmount = '0.00'
        return
      }
      
      const num = typeof value === 'string' ? parseFloat(value) : value
      if (!isNaN(num)) {
        item.totalAmount = num.toFixed(2)
      } else {
        item.totalAmount = '0.00'
      }
    }

    // 处理费用字段变化
    const onFeeFieldChange = (value, item, field) => {
      // 允许数字、小数点和负号
      let filteredValue = value.replace(/[^\d.-]/g, '')
      
      // 确保只有一个小数点
      const parts = filteredValue.split('.')
      if (parts.length > 2) {
        filteredValue = parts[0] + '.' + parts.slice(1).join('')
      }
      
      item[field] = filteredValue
      
      // 如果对应的成本明细字段存在，同步更新
      if (item.costs && item.costs.hasOwnProperty(field)) {
        item.costs[field] = filteredValue
      }
    }

    // 格式化费用字段
    const formatFeeField = (item, field) => {
      const value = item[field]
      if (value === null || value === undefined || value === '') {
        item[field] = '0.00'
        if (item.costs && item.costs.hasOwnProperty(field)) {
          item.costs[field] = '0.00'
        }
        return
      }
      
      const num = typeof value === 'string' ? parseFloat(value) : value
      if (!isNaN(num)) {
        const formattedValue = num.toFixed(2)
        item[field] = formattedValue
        if (item.costs && item.costs.hasOwnProperty(field)) {
          item.costs[field] = formattedValue
        }
      } else {
        item[field] = '0.00'
        if (item.costs && item.costs.hasOwnProperty(field)) {
          item.costs[field] = '0.00'
        }
      }
    }

    // 添加自定义字段
    const addCustomField = (item) => {
      if (!item.customFields) {
        item.customFields = []
      }
      item.customFields.push({
        name: '',
        value: '0.00'
      })
    }

    // 删除自定义字段
    const removeCustomField = (item, index) => {
      if (item.customFields && index >= 0 && index < item.customFields.length) {
        item.customFields.splice(index, 1)
      }
    }

    // 处理自定义字段值变化
    const onCustomFieldChange = (value, customField) => {
      // 允许数字、小数点和负号
      let filteredValue = value.replace(/[^\d.-]/g, '')
      
      // 确保只有一个小数点
      const parts = filteredValue.split('.')
      if (parts.length > 2) {
        filteredValue = parts[0] + '.' + parts.slice(1).join('')
      }
      
      customField.value = filteredValue
    }

    // 格式化自定义字段
    const formatCustomField = (customField) => {
      const value = customField.value
      if (value === null || value === undefined || value === '') {
        customField.value = '0.00'
        return
      }
      
      const num = typeof value === 'string' ? parseFloat(value) : value
      if (!isNaN(num)) {
        customField.value = num.toFixed(2)
      } else {
        customField.value = '0.00'
      }
    }
    
    // 计算总金额 - 自动累加所有物料的合计金额
    const computedTotalAmount = computed(() => {
      if (!quotationForm.items || quotationForm.items.length === 0) {
        return 0
      }
      
      return quotationForm.items.reduce((total, item) => {
        const amount = typeof item.totalAmount === 'string' ? parseFloat(item.totalAmount) : item.totalAmount
        return total + (isNaN(amount) ? 0 : amount)
      }, 0)
    })

    // 监听总金额变化，更新表单的totalAmount字段
    watch(computedTotalAmount, (newValue) => {
      quotationForm.totalAmount = newValue.toFixed(2)
    })

    // 组件挂载时的初始化
    onMounted(() => {
      fetchCustomers()
      fetchEmployees()
      // 默认添加一个物料项
      addItem()
      // 设置默认订单日期为当天
      quotationForm.orderDate = new Date().toISOString().split('T')[0]
    })
    
    return {
      quotationFormRef,
      saving,
      submitting,
      generating,
      quotationForm,
      customers,
      employees,
      rules,
      addItem,
      removeItem,
      calculateAmount,
      calculateTotalCost,
      getCostTotal,
      calculateTotalAmount,
      handleCustomerChange,
      handleCustomerNameChange,
      getStatusTagType,
      saveDraft,
      submitQuotation,
      handleGenerateContract,
      formatDisplayNumber,
      formatNumber,
      formatUnitPrice,
      preprocessQuotationData,
      postprocessQuotationData,
      onQuantityChange,
      onUnitPriceChange,
      onCalculationFieldChange,
      onCostFieldChange,
      onItemAmountChange,
      formatItemAmount,
      onFeeFieldChange,
      formatFeeField,
      addCustomField,
      removeCustomField,
      onCustomFieldChange,
      formatCustomField,
      computedTotalAmount,
      // 自定义下拉选择框处理方法
      handleLayersChange,
      handleThicknessChange,
      handleSurfaceTreatmentChange,
      handleSolderMaskChange,
      handleCharacterChange,
      handleInnerCopperChange,
      handleOuterCopperChange,
      handleViaProcessChange,
      handleTestingChange
    }
  }
}
</script>

<style>
.quotation-form {
  margin: 20px;
  max-width: 1400px;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid #e4e7ed;
}

.form-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.actions {
  display: flex;
  gap: 12px;
}

.form-section {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.card-header span {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

/* 物料卡片样式 */
.item-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  margin-bottom: 20px;
  background: #fafafa;
  transition: all 0.3s ease;
}

.item-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.1);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: linear-gradient(135deg, #409eff, #66b3ff);
  color: white;
  border-radius: 8px 8px 0 0;
  margin-bottom: 0;
}

.item-title {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
}

.item-header .el-button {
  border-color: rgba(255, 255, 255, 0.3);
  color: white;
  background: rgba(255, 255, 255, 0.1);
}

.item-header .el-button:hover {
  background: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.5);
}

/* 信息区域样式 */
.info-section {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.info-section:last-child {
  border-bottom: none;
}

.section-subtitle {
  font-size: 14px;
  font-weight: 600;
  color: #606266;
  margin: 0 0 16px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #e4e7ed;
  position: relative;
}

.section-subtitle::before {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 40px;
  height: 2px;
  background: #409eff;
}

/* 表单项样式优化 */
:deep(.el-form-item) {
  margin-bottom: 16px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
  font-size: 14px;
}

:deep(.el-form-item__content) {
  line-height: 1.5;
}

/* 输入框样式优化 */
:deep(.el-input) {
  width: 100%;
}

:deep(.el-input__inner) {
  border-radius: 4px;
  transition: all 0.3s ease;
  font-size: 14px;
}

:deep(.el-input__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

:deep(.el-input.is-disabled .el-input__inner) {
  background-color: #f8f9fa;
  border-color: #e9ecef;
  color: #6c757d;
}

/* 选择框样式优化 */
:deep(.el-select) {
  width: 100%;
}

:deep(.el-select .el-input__inner) {
  cursor: pointer;
}

/* 数字输入框样式 */
.number-input :deep(.el-input__inner) {
  text-align: center;
  font-family: 'Consolas', 'Monaco', monospace;
  font-weight: 500;
}

/* 日期选择器样式 */
:deep(.el-date-editor) {
  width: 100%;
}

:deep(.el-date-editor .el-input__inner) {
  cursor: pointer;
}

/* 按钮样式优化 */
:deep(.el-button) {
  border-radius: 4px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #409eff, #66b3ff);
  border: none;
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #66b3ff, #409eff);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

:deep(.el-button--success) {
  background: linear-gradient(135deg, #67c23a, #85ce61);
  border: none;
}

:deep(.el-button--success:hover) {
  background: linear-gradient(135deg, #85ce61, #67c23a);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
}

:deep(.el-button--danger) {
  background: linear-gradient(135deg, #f56c6c, #f78989);
  border: none;
}

:deep(.el-button--danger:hover) {
  background: linear-gradient(135deg, #f78989, #f56c6c);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
}

/* 标签样式 */
:deep(.el-tag) {
  font-weight: 500;
  border-radius: 16px;
  padding: 8px 16px;
}

:deep(.el-tag--large) {
  font-size: 14px;
  padding: 10px 20px;
}

/* 卡片样式优化 */
:deep(.el-card) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-card__header) {
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  padding: 16px 20px;
}

:deep(.el-card__body) {
  padding: 20px;
}

/* 栅格系统间距优化 */
.el-row {
  margin-left: -7.5px !important;
  margin-right: -7.5px !important;
}

.el-col {
  padding-left: 7.5px !important;
  padding-right: 7.5px !important;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .quotation-form {
    margin: 15px;
  }
  
  .form-header h2 {
    font-size: 20px;
  }
  
  .actions {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .info-section {
    padding: 15px;
  }
}

@media (max-width: 768px) {
  .quotation-form {
    margin: 10px;
  }
  
  .form-header {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .actions {
    justify-content: center;
  }
  
  .card-header {
    flex-direction: column;
    gap: 12px;
  text-align: center;
}

  .item-header {
    flex-direction: column;
    gap: 12px;
  text-align: center;
  }
  
  .info-section {
    padding: 12px;
  }
  
  :deep(.el-form-item__label) {
    text-align: left !important;
    margin-bottom: 8px;
  }
}

/* 加载状态优化 */
:deep(.el-loading-mask) {
  border-radius: 8px;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 动画效果 */
.item-card {
  animation: fadeInUp 0.3s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 打印样式 */
@media print {
  .form-header .actions,
  .item-header .el-button {
    display: none;
  }
  
  .item-card {
    border: 1px solid #000;
    box-shadow: none;
    page-break-inside: avoid;
  }
  
  .info-section {
    page-break-inside: avoid;
  }
}

/* 只读字段样式 */
:deep(.readonly-field .el-input__inner) {
  background-color: #f5f7fa !important;
  border-color: #e4e7ed !important;
  color: #909399 !important;
  cursor: not-allowed !important;
}

:deep(.readonly-field.is-disabled .el-input__inner) {
  background-color: #f5f7fa !important;
  border-color: #e4e7ed !important;
  color: #909399 !important;
}

/* 费用明细区域样式 */
.fee-section {
  margin-top: 16px;
  padding: 16px;
  background: #fafbfc;
  border-radius: 6px;
  border: 1px solid #ebeef5;
}

/* 费用明细标题样式 */
.fee-subtitle {
  font-size: 13px;
  font-weight: 600;
  color: #606266;
  margin: 0 0 12px 0;
  padding-bottom: 6px;
  border-bottom: 1px solid #e4e7ed;
  position: relative;
}

.fee-subtitle::before {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 30px;
  height: 2px;
  background: #67c23a;
}

/* 自定义字段区域样式 */
.custom-fields-section {
  margin-top: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.custom-field-row {
  margin-bottom: 12px;
}

.custom-field-row:last-child {
  margin-bottom: 0;
}
</style> 